package com.itheima.web.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = {"/system/*","/store/*"})
public class PermissionFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //权限校验的原则：对于查询类的方法，只要用户登录成功了就运行访问，此处不进行拦截。对于增删改类的方法进行权限校验
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;

        //1 获取访问路径
        String servletPath = request.getServletPath(); //得到 /system/user、 /system/dept ....
        String pathInfo = request.getPathInfo(); //得到  /findByPage  /save  /delete  /edit /update ...

        //2 如果访问路径是查询类的，应该直接放行
        if(pathInfo.substring(1).startsWith("find") || pathInfo.substring(1).startsWith("select")){
            chain.doFilter(req, resp);
            return;
        }

        //3 获取该用户的权限列表，进行权限校验
        //3.1 获取权限列表
        List<String> curls = (List<String>) request.getSession().getAttribute("curls");
        //3.2 开始校验
        if(curls.contains(servletPath+pathInfo)){ // servletPath+pathInfo= /system/user/save
            //校验通过，放行
            chain.doFilter(req, resp);
        }else{
            //校验失败，响应错误信息json
            ObjectMapper objectMapper=new ObjectMapper();
            objectMapper.writeValue(response.getOutputStream(),new Result(false, MessageConstant.PERMISSION_FORBIDDEN));
        }

    }

    public void init(FilterConfig config) throws ServletException {}
    public void destroy() {}

}
